package com.example.blemulticondemo.utils;

/**
 * @author linvisf
 * @date 2024/8/6.
 * description：
 */
public class ByteToHexUtil {

    public static String convertStringToHex(String str) {
        char[] chars = str.toCharArray();

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            sb.append(Integer.toHexString(chars[i]));
        }
        return sb.toString();
    }

    public static String convertHexToString(String hex) {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        // 564e3a322d302e312e34 split into two characters 56, 4e, 3a...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            // grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            // convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            // convert the decimal to character
            sb.append((char) decimal);

            temp.append(decimal);
        }
        // System.out.println(sb.toString());
        return sb.toString();
    }

    /**
     * byte数组转16进制字符串
     *
     * @param bArray
     * @return
     */
    public static String byteToHexString(byte bArray) {
        StringBuffer sb = new StringBuffer();
        String sTemp = Integer.toHexString(0xFF & bArray);
        if (sTemp.length() < 2)
            sb.append(0);
        sb.append(sTemp.toUpperCase());
        return sb.toString();
    }

    /**
     * byte数组转16进制字符串
     *
     * @param bArray
     * @param size
     * @return
     */
    public static String byteToHexString(byte[] bArray, final int size) {
        StringBuffer sb = new StringBuffer(size + size / 2);
        String sTemp;
        for (int i = 0; i < size; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static int byte4ToInt(byte[] b) {
        return b[3] & 0xFF |
                (b[2] & 0xFF) << 8 |
                (b[1] & 0xFF) << 16 |
                (b[0] & 0xFF) << 24;
    }

    /**
     * 8个字节转double。 注意大小端
     *
     * @param arr
     * @return
     */
    public static double bytes8ToDouble(byte[] arr) {
        long value = 0;
        for (int i = 0; i < 8; i++) {
            value |= ((long) (arr[7 - i] & 0xff)) << (8 * i);
        }
        return Double.longBitsToDouble(value);
    }
}
